from asyncio import iscoroutinefunction

from mg_app_framework import RabbitMQConfigBasic, get_logger, rabbitmq_publish_one


class RabbitMQConfig(RabbitMQConfigBasic):

    # def get_rabbitmq_host(self):
    #     return "192.168.20.143"

    # def get_rabbitmq_port(self):
    #     return "5672"

    # def get_rabbitmq_username(self):
    #     return "rabbitmq"

    # def get_rabbitmq_password(self):
    #     return "realtech@123"

    def ack_before_message_process_func(self):
        """
        设置, mq消息处理返回ack的时机
        :return:
            True: 在处理mq消息之前, 返回ack
            False: 处理mq消息之后, 返回ack
        """
        return False

    def get_rabbitmq_subscribe_list(self):
        """
        :return:返回订阅的数组
        [
            'kkk', # 消息索引
            'yyy', # 消息索引
            ...
        ]
        """
        return list(mq_process_mapper.keys())

    def message_process_func(self):
        """
        1. subscribe_list is not empty
        2. when receive message, call this function to process message
        message 数据格式:
        {
            'key'  : 'kkk',  # 消息索引
            'data' : {}      # 消息数据
        }
        """
        return process_mq_msg


async def process_mq_msg(msg):
    # 对接收到的消息做初步判断，并分发给对应的处理函数
    msg_key = msg.get("key", None)
    msg_data = msg.get("data", None)
    if not msg_key:
        get_logger().error("msg key is None")
        return
    msg_process_func = mq_process_mapper.setdefault(msg_key, None)
    if not msg_process_func:
        get_logger().error("there is not process func for mq key:{}".format(msg_key))
        return
    if iscoroutinefunction(msg_process_func):
        await msg_process_func(msg_data)
    else:
        msg_process_func(msg_data)


async def send_rabbitmq(*, key, data, time_series_data=True):
    await rabbitmq_publish_one(data={"key": key, "data": data}, time_series_data=time_series_data)
    get_logger().info("successfully send MQ to " + key + " " + str(data))


# 最好不要执行订阅操作，有更改在调整
mq_process_mapper = {}
